import json

from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from rest_framework.authtoken.models import Token

from user.models import Staff

class PermissionCheck():
    def __init__(self, code=None):
        self.code = code

    def get_token(self, request):
        credential = request.META.get('HTTP_AUTHORIZATION')
        if credential:
            self.token = credential.split()[-1]
            return self.token

    @property
    def user(self):
        return Token.objects.get(pk=self.token).user

    def __call__(self, view_func):
        this_ = self
        def wrapper(*args, **kwargs):
            if isinstance(args[0], WSGIRequest):
                request = args[0]
            else:
                request = args[1]
            # get request user
            token = this_.get_token(request)
            if token:
                user: Staff = this_.user
                print(user.get_group_permissions())
                print('PermissionCheck------', this_.user, self.code , self.code in user.get_group_permissions())
                if self.code in user.get_group_permissions():
                    ret = view_func(*args, **kwargs)
                    return ret
                else:
                    return HttpResponse(content=json.dumps({'msg':'User no Permission'}).encode('utf-8'),
                                       content_type='application/json;charset=utf-8')
            return HttpResponse(content=json.dumps({'msg':'User no Login'}).encode('utf-8'),
                                       content_type='application/json;charset=utf-8')
        return wrapper